class PriceStore {
  
  private static inited = false
  private static tokenPricesUpdateTime = 0
  private static cashPricesUpdateTime = 0

  static tokenPrices = null as any
  static cashPrices = null as any

  private static async fetchTokenPrices() {
    const res = await fetch(
      "https://api.compound.finance/api/v2/prices?network=mainnet"
    );
    const data = await res.json();
    if (data.error) {
      alert(data.error);
      return;
    }
    PriceStore.tokenPrices = [
      { symbol: "WHT", price: "1" },
      { symbol: "WBNB", price: "1" },
    ]
    data.tokens.forEach((item:any) => {
      PriceStore.tokenPrices.push(item)
    });
  }

  private static async fetchCashPrices() {
    const res = await fetch(
      "https://v6.exchangerate-api.com/v6/0cd7ce4b5ab2127bc2c93606/latest/USD"
    );
    const data = await res.json();
    if (data.result != "success") {
      alert("error when get cash price");
      return;
    }
    PriceStore.cashPrices = data.conversion_rates;
  }

  private static async init() {
    await PriceStore.fetchTokenPrices()
    await PriceStore.fetchCashPrices()
    // console.log('## price');
    // console.log(PriceStore.tokenPrices);
    // console.log(PriceStore.cashPrices);
    PriceStore.inited = true
  }

  static async tryInit() {
    if (!PriceStore.inited) {
      await PriceStore.init()
    }
  }
}

// get token price by cash
// Exam: usePrice("ETH", "CNY")
export async function usePrice(token: string, cash: string) {
  const _token = token == "WETH" ? "ETH" : token;
  await PriceStore.tryInit()
  
  
  const tokenToUsd = parseFloat(
    PriceStore.tokenPrices.filter((item:any) => item.symbol == _token)[0].price
  );
  const usdToCash = PriceStore.cashPrices[cash];

  return tokenToUsd * usdToCash;
}